package code.structure.module.scene.model
{
	import com.patience.mvc.context.Command;
	
	import flash.events.Event;
	import flash.utils.Dictionary;
	
	import code.main.AppCommonData;
	import code.main.AppData;
	import code.main.core.mvc.YModelData;
	import code.structure.module.configs.ConfigModel;
	import code.structure.module.configs.data.AreaConfigData;
	import code.structure.module.configs.data.ItemConfigData;
	import code.structure.module.scene.model.data.SceneItemData;
	import code.structure.module.scene.model.data.SceneUserData;
	import code.structure.module.scene.view.iso.WallMuralIsoObject;
	import code.structure.module.scene.view.iso.YIsoObject;
	import code.structure.module.scene.view.iso.product.ProductPloughIsoObject;
	import code.structure.module.scene.view.iso.product.base.ProductIsoObject;
	import code.structure.module.user.UserModel;
	import code.untils.GameConst;
	import code.untils.NetConst;
	import code.untils.NetDataBackKeyConst;
	import code.untils.SceneConfig;
	import code.untils.SystemFunction;
	
	/**
	 *场景数据
	 * @author Yuri
	 */
	public class SceneModel extends YModelData
	{
		//配置信息
		private var _configModel:ConfigModel;
		//用户信息
		private var _userModel:UserModel;
		//存储地图数据
		private var _dictionary:Dictionary;
		//是否自己的场景
		private var _isMyScene:Boolean = true;
		//是否GM的场景
		private var _isGMScene:Boolean = false;
		//是否第一次加载 统计物品数量
		private var _isFirst:Boolean = true;
		/**
		 * 解锁的区块
		 */
		public var unlockArea:Array = [];
		/**
		 * 当前场景的人物信息
		 */
		private var _scencUserData:SceneUserData;
		//场景初始数据<来自后台>
		private var _sceneData:Object;
		public function SceneModel()
		{
			super();
			_configModel = (_context.commonData as AppCommonData).configModel;
			_userModel = (_context.commonData as AppCommonData).userModel;
			requestGetSceneData();
		}
		
		private function requestGetSceneData():void
		{
			_net.addEventListener(NetDataBackKeyConst.SCENE_DATA, recevieMapData);
		}
		
		private function recevieMapData(e:Event):void
		{
			_sceneData = e;
			analyMapData(_sceneData);
		}
		
		private function analyMapData(e:Object):void{
			//确认当前是哪个场景自己的还是别人的
			_isMyScene = (e.data.userInfo.uid == AppData.myId);
			_isGMScene = (e.data.userInfo.uid == GameConst.GAME_MANAGER_ID);
			AppData.isMyScene = _isMyScene;
			//相应的数据生成
			_scencUserData = new SceneUserData(e.data.userInfo);
			if (e.data.userInfo.map_unlock)
				unlockArea = JSON.parse(e.data.userInfo.map_unlock) as Array;
			//数据确认
			_isFirst = false;
		}
		
		/**
		 *解析场景对象地图数据 
		 */
		private function analySceneInfoData(obj:Object):void{
			_dictionary = new Dictionary();
			var _obj:Object;
			var _item:SceneItemData;
			var _shopItem:ItemConfigData;
			for each (_obj in obj.userMap)
			{
				_item = SceneItemData.parserData(_obj);
				_item.data = _configModel.getItemConfigData(_item.itemID);
				if(!_item.data && !AppData.isMyScene) continue; //防止访问好友家里AB配置表不同读不到物品
				//保存最大的地图场景ID 用于新建时自增
				if(AppData.isMyScene && Number(_item.id) > SceneConfig.SCENE_MAX_MAP_ID)
					SceneConfig.SCENE_MAX_MAP_ID = Number(_item.id);
				if (_item.endTime != -1){
					_item.endTime -= SystemFunction.serverTime;
				}
				if (_item.bind_id != 0){
					_item.bindingData = _configModel.getItemConfigData(_item.bind_id);
				}
				if (_item.output_id != 0 && _item.output_num != 0 && _item.endTime != -1)
					_item.outputData = _configModel.getItemConfigData(_item.output_id);
				
				_dictionary[_item.id] = _item;
			}
		}
		private var isFirstLoad:Boolean = true; //是否第一次加载游戏
		
		/**
		 * 清除枯萎 过期
		 * @return
		 */
		public function clearWither(value:YIsoObject):Boolean
		{
			_netManager.addNetCmdDetail(NetConst.CLASS_MAP, NetConst.FUN_CLEAR_MAP_ITEM, [value.id]);
			return true;
		}
		
		/**
		 * 地图操作处理
		 * @param value 地图数据
		 * @param type  操作类型 1:添加 2:移动 3:旋转 4:出售 5:回收到仓库
		 */
		public function diyMapItem(value:YIsoObject, type:int):Boolean
		{
			if(!AppData.isMyScene) return false;
			if (!value.id && (type == 2 || type == 1)) {
				value.data.id = value.id = String(++ SceneConfig.SCENE_MAX_MAP_ID);
				type = 1;
			}
			recordInitialValue(value.data, value, true); //记录初始数据 并为回退做准备
			if (value is WallMuralIsoObject) {
				(value as WallMuralIsoObject).data.bindWall = (value as WallMuralIsoObject).getWallAttachIdList();
			}
			switch (type) {
				case 1: 
					var bl:Boolean = addMapItem(value);
					if(!bl) value.data.id = value.id = null;
					return bl;
					break;
				case 2: 
					moveMapItem(value.data);
					break;
				case 3: 
					rotateMapItem(value.data);
					break;
				case 4: 
					return sellMapItem(value.data, value);
					break;
				case 5: 
					return recoverMapItem(value.data, value);
					break;
			}
			return true;
		}
		
		//添加地图物品
		private function addMapItem(iso:YIsoObject):Boolean
		{
			var state:int;	//购买方式<系统生成|仓库|购买>
			if(!_userModel.changeMoney(-iso.data.data.buyCost, iso.data.data.buyType)) return false;
			_netManager.addNetCmdDetail(NetConst.CLASS_MAP, NetConst.FUN_ADD_MAP_ITEM,[iso.id, iso.data.data.id, iso.gridX+"|"+iso.gridZ, iso.direction, state, iso.data.bindWall]);
			_dictionary[iso.id] = iso.data;
			return true;
		}
		
		//移动地图上的物品
		private function moveMapItem(value:SceneItemData):void
		{
			_netManager.addNetCmdDetail(NetConst.CLASS_MAP, NetConst.FUN_MOVE_MAP_ITEM, [value.id, value.x+"|"+value.z, value.direction, value.bindWall]);
		}
		
		//旋转地图上的物品
		private function rotateMapItem(value:SceneItemData):void
		{
			_netManager.addNetCmdDetail(NetConst.CLASS_MAP, NetConst.FUN_ROTATE_MAP_ITEM, [value.id, value.direction]);
		}
		
		//出售地图上的物品
		private function sellMapItem(value:SceneItemData, iso:YIsoObject):Boolean
		{
			if (value.data.sellCost < 0){
				//dispatch(new Command(CommandNameConst.COMMAND_WARN_MSG_ALERT,"WARN_3"));
				return false; //禁止出售
			}
			_netManager.addNetCmdDetail(NetConst.CLASS_MAP, NetConst.FUN_SELL_MAP_ITEM, [value.id]);
			_userModel.changeMoney(value.data.sellCost, value.data.sellType);
			delete _dictionary[value.id];
			return true;                                                                                                                                                 
		}
		
		//回收到仓库
		private function recoverMapItem(value:SceneItemData, iso:YIsoObject):Boolean
		{
			if(false){ //无法回收
				return false;
			}
			_netManager.addNetCmdDetail(NetConst.CLASS_MAP, NetConst.FUN_RECOVER_MAP_ITEM, [value.id]);
			delete _dictionary[value.id];
			return true;
		}
		
		//复活场景上的物品
		public function easterSceneItem(iso:YIsoObject):Boolean
		{
			_netManager.addNetCmdDetail(NetConst.CLASS_MAP, NetConst.FUN_EASTER_MAP_ITME, [iso.id]);
			return true;
		}
		/**
		 *种植种子
		 * @param iso
		 */
		public function plantSeed(iso:ProductPloughIsoObject):Boolean
		{
			_netManager.addNetCmdDetail(NetConst.CLASS_MAP, NetConst.FUN_PLANT, [iso.id, iso.productShopItemData.id]);
			return true
		}
		/**
		 * 收获 第二个参数随机掉落物
		 */		
		public function harvest(iso:YIsoObject):Boolean
		{
			_netManager.addNetCmdDetail(NetConst.CLASS_MAP, NetConst.FUN_HARVEST, [iso.id, 0]);
			return true;
		}
		/**
		 * 清除土地上的种子
		 * @param	iso
		 */
		public function clearSeed(iso:ProductPloughIsoObject):Boolean
		{
			_netManager.addNetCmdDetail(NetConst.CLASS_MAP, NetConst.FUN_CLEAR_MAP_ITEM, [iso.id]);
			return true;
		}
	
		/**
		 * 解锁地图区块 6_4食谱研发的地块
		 * @param data
		 * @param isOff 是否条件五折
		 * @return 
		 * 
		 */		
		public function unlockMapArea(data:AreaConfigData,isOff:Boolean = false):Boolean
		{
			//检测值 扣值
//			_netManager.addNetCmdDetail(NetConst.CLASS_MAP, NetConst.FUN_UNLOCKAREA, [data.unlock_map_xy]);
			
			/*var meta:MetaActiveData;
			for (var i:int = 0; i < data.unlock_require.length; i += 1){
				meta = data.unlock_require[i];
				if(meta.isCostSkill)continue;//花钱跳过的不扣
				if(meta.type == 0){
					var costNum:int = meta.num > 1 && isOff ? Math.ceil(meta.num * .5) : meta.num;
					_storageModel.addStorageData(meta.shopItem, -costNum, true, true);
				}
			}
			unlockArea.push(data.unlock_map_xy);
			_userModel.baseData.aUnlockMap.push(data.unlock_map_xy);
			ProjectAssistManager.getIntance().triggerDataManager.analyActionTriggerTask(TaskTypeConst.TYPE_EXPAND_APPOINT_AREA, data.unlock_map_xy, 1, true);
			var arr:Array = _configModel.analyStaticSceneInfo.getAreaStaticMapInfoByKey(data.unlock_map_xy);
			if(arr){
				var sceneItem:SceneItemData;
				for (var j:int = 0; j < arr.length; j++) {
					sceneItem = arr[j];
					if(sceneItem){
						recountItemNo(sceneItem.data, 1);
						sceneItem.data.lockNum -= 1;
						_dictionary[sceneItem.id] = sceneItem;
					}
				}
			}
			_taskModel.recountOwnForSell();*/
			return true;
		}
		
		
		/**
		 * 判断区块是否解锁
		 * @param	id
		 * @return
		 */
		public function areaUnlockable(id:String):Boolean {
			return unlockArea.indexOf(id) >= 0;
		}
		
	
		/**
		 * 地图数据
		 */
		public function get dictionary():Dictionary { return _dictionary; }
		
		public function get isMyScene():Boolean { return _isMyScene; }
		public function set isMyScene(value:Boolean):void { _isMyScene = value; }
		
		/**
		 * 配置表
		 */
		public function get configModel():ConfigModel { return _configModel; }
		
		/**
		 * 记录物品的初始信息 如果操作返回false回退
		 * @param	scene
		 * @param	iso
		 * @param	record
		 */
		private function recordInitialValue(scene:SceneItemData, iso:YIsoObject, record:Boolean):void
		{
			scene.x = iso.gridX;
			scene.z = iso.gridZ;
			scene.direction = iso.direction;
			scene.position3D = iso.position3D;
		}
		
		public function addNetCallBack(type:String,listener:Function):void
		{
			_net.addEventListener(type, listener);
		}
		
		
		public function get isGMScene():Boolean { return _isGMScene; }

	}
}